package com.computergames.server.protocol;

import com.computergames.server.message.Message;
import com.computergames.server.message.chessMessage.AbstractChessMessage;
import com.computergames.server.message.chessMessage.GobangMessage;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;

import java.io.IOException;

public class ChessMessageDeserializer extends StdDeserializer<AbstractChessMessage> {

    public ChessMessageDeserializer() {
        this(null);
    }

    public ChessMessageDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public AbstractChessMessage deserialize(JsonParser p, DeserializationContext ctx) throws IOException {
        JsonNode node = p.getCodec().readTree(p);

        // 获取messageType
        int messageType = node.get("messageType").asInt();

        // 根据messageType创建对应的子类实例
        switch (messageType) {
            case Message.GobangMessage:
                return deserializeGobang(node);
            // 添加更多case处理其他messageType
            default:
                throw ctx.weirdStringException(node.toString(), AbstractChessMessage.class, "Unknown messageType: " + messageType);
        }
    }

    private GobangMessage deserializeGobang(JsonNode node) throws IOException {
        String chess = node.get("chess").asText();
        String[] coordinates = new String[node.get("coordinate").size()];
        for (int i = 0; i < node.get("coordinate").size(); i++) {
            coordinates[i] = node.get("coordinate").get(i).asText();
        }
        return new GobangMessage(chess, coordinates);
    }
}
